<template>
  <div>
    <!-- 悬浮按钮 -->
    <div class="float-button-wrapper">
      <div class="float-button disFlxCC" @click="showChat = true">
        <div class="button-content disFlxCC">
          <i class="el-icon-chat-dot-round"></i>
          <span class="ai-text">AI</span>
        </div>
        <!-- 添加动态光环效果 -->
        <div class="pulse-ring"></div>
      </div>
    </div>

    <!-- 聊天窗口 -->
    <el-dialog
      title="AI 助手"
      :visible.sync="showChat"
      :close-on-click-modal="false"
      width="60%"
      custom-class="padding10"
      append-to-body
    >
      <div class="chat-container">
        <!-- 对话历史 -->
        <div class="chat-history" ref="chatHistory">
          <div
            v-for="(msg, index) in chatHistory"
            :key="index"
            :class="['message disFlxAC', msg.role]"
          >
            <!-- 用户消息 -->
            <template v-if="msg.role === 'user'">
              <div class="avatar shrink0">
                <img :src="userAvatar" alt="用户头像" />
              </div>
              <div class="content" v-html="renderMessage(msg.content)"></div>
            </template>
            <!-- AI助手消息 -->
            <template v-if="msg.role === 'assistant'">
              <div class="avatar ai-avatar disFlxCC shrink0">
                <span class="ai-text">AI</span>
              </div>
              <div class="content" :class="{ typing: msg.isTyping }">
                <span class="message-content">
                  <span v-html="renderMessage(msg.content)"></span>
                  <span
                    v-if="isThinking && msg === currentTypingMessage"
                    class="typing-indicator"
                  >
                    <i></i><i></i><i></i>
                  </span>
                </span>
              </div>
            </template>
            <!-- 系统消息 -->
            <template v-if="msg.role === 'system'">
              <div class="content tc" v-html="renderMessage(msg.content)"></div>
            </template>
          </div>
        </div>

        <!-- 推荐提示词部分 -->
        <div
          v-if="showRecommends && recommendPrompts.length"
          class="recommend-prompts"
        >
          <div class="recommend-title">你可能想问：</div>
          <div class="recommend-list">
            <div
              v-for="(prompt, index) in recommendPrompts"
              :key="index"
              class="recommend-item"
              @click="handleRecommendClick(prompt)"
            >
              {{ prompt }}
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <div class="input-wrapper">
            <el-input
              v-model="userInput"
              type="textarea"
              :rows="3"
              :maxlength="1000"
              show-word-limit
              resize="none"
              placeholder="输入您的问题，按回车发送，Shift + 回车换行"
              @keydown.enter.native.exact.prevent="sendMessage"
              @keydown.enter.native.shift.exact.prevent="handleShiftEnter"
            />
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'  // 引入 mapState
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'

export default {
  name: 'AiChat',
  data() {
    return {
      showChat: false,    // 控制聊天窗口显示
      chatHistory: [],    // 对话历史记录
      userInput: '',      // 用户输入
      loading: false,     // 加载状态
      welcomeMessage: '👋 你好！我是你的 AI 助手，有什么我可以帮你的吗？', // 欢迎消息
      isThinking: false, // @comment 控制思考动画
      currentTypingMessage: null, // @comment 当前正在打字的消息
      md: new MarkdownIt({
        highlight: function (str, lang) {
          if (lang && hljs.getLanguage(lang)) {
            try {
              return hljs.highlight(lang, str).value
            } catch (__) { }
          }
          return str
        }
      }),
      recommendPrompts: [], // 存储推荐提示词
      showRecommends: false, // 控制推荐提示词的显示
      apiKey: 'sk-e61572c5ee704f24aca14da0193f4573', // 从环境变量获取API key
      systemPrompt: `你是一个AI助手，请用JSON格式回复所有问题。
回复格式要求：
1. 必须是合法的JSON格式
2. 包含以下字段：
   - response: 主要回复内容
   - suggestions: 相关的推荐问题数组
   - status: 处理状态("success"/"error")
示例输出：
{
  "response": "这是回复的主要内容",
  "suggestions": ["相关问题1", "相关问题2"],
  "status": "success"
}`,
    }
  },
  computed: {
    ...mapState({
      userAvatar: state => state.user.avatar  // 从 vuex 获取用户头像
    })
  },
  watch: {
    // 监听对话窗口显示状态
    showChat(val) {
      if (val) {
        // 如果聊天历史为空，添加欢迎消息
        if (this.chatHistory.length === 0) {
          this.chatHistory.push({
            role: 'assistant',
            content: this.welcomeMessage
          })
        }
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
    }
  },
  methods: {
    // 发送消息
    async sendMessage() {
      if (!this.userInput.trim() || this.loading) return

      const userMessage = {
        role: 'user',
        content: this.userInput
      }

      // 只保留最近的10条消息历史
      const recentMessages = this.chatHistory.slice(-10)

      const messages = [
        {
          role: 'system',
          content: this.systemPrompt
        },
        ...recentMessages,
        userMessage
      ]

      this.chatHistory.push(userMessage)
      this.loading = true
      this.isThinking = true
      this.userInput = ''

      try {
        const aiMessage = {
          role: 'assistant',
          content: '',
          isTyping: true
        }
        this.chatHistory.push(aiMessage)
        this.currentTypingMessage = aiMessage

        const response = await fetch('https://api.deepseek.com/chat/completions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.apiKey}`
          },
          body: JSON.stringify({
            model: 'deepseek-chat',
            messages,
            response_format: { type: 'json_object' },
            // 代码生成/数学解题	0.0
            // 数据抽取/分析	1.0
            // 通用对话	1.3
            // 翻译	1.3
            // 创意类写作/诗歌创作	1.5
            temperature: 1.3,
            stream: false // 是否流式输出
          })
        })

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        // 修改这里：直接使用 response.json() 获取完整响应
        const responseData = await response.json()
        console.log(responseData, 1111);
        try {
          // 解析AI助手返回的JSON字符串
          const jsonResponse = JSON.parse(responseData.choices[0].message.content)

          // 更新AI消息内容
          aiMessage.content = jsonResponse.response

          // 更新推荐提示词
          this.recommendPrompts = jsonResponse.suggestions || []
          this.showRecommends = Boolean(this.recommendPrompts.length)

          // 更新状态
          aiMessage.isTyping = false
          this.currentTypingMessage = null
          this.isThinking = false

          this.$forceUpdate()
          this.scrollToBottom()
        } catch (e) {
          console.error('解析AI响应JSON失败:', e)
          aiMessage.content = '⚠️ 解析响应数据失败'
        }

      } catch (error) {
        console.error('API请求错误:', error)
        this.$message.error('请求失败: ' + (error.message || '请检查API配置是否正确'))

        this.chatHistory.push({
          role: 'system',
          content: '⚠️ 抱歉，API调用出现异常，请稍后重试'
        })
      } finally {
        this.loading = false
        this.scrollToBottom()
      }
    },

    // 渲染消息内容
    renderMessage(content) {
      try {
        return this.md.render(content)
      } catch (e) {
        console.error('渲染消息失败:', e)
        return content
      }
    },

    // 滚动到底部
    scrollToBottom() {
      const container = this.$refs.chatHistory
      container.scrollTop = container.scrollHeight
    },

    // 处理 Shift + Enter 换行
    handleShiftEnter(e) {
      // 在光标位置插入换行符
      const start = e.target.selectionStart
      const end = e.target.selectionEnd
      const text = this.userInput
      this.userInput = text.substring(0, start) + '\n' + text.substring(end)
      // 下一帧更新光标位置
      this.$nextTick(() => {
        e.target.selectionStart = e.target.selectionEnd = start + 1
      })
    },

    // 处理推荐提示词点击
    handleRecommendClick(prompt) {
      this.userInput = prompt; // 将选中的提示词填入输入框
      this.sendMessage(); // 可选：直接发送消息
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/mixin.scss";
::v-deep .padding10 .el-dialog__body {
  padding: 0 10px;
}

.float-button-wrapper {
  position: fixed;
  right: 20px;
  bottom: 30px;
  z-index: 2000;
}

.float-button {
  position: relative;
  width: 50px;
  height: 50px;
  background: linear-gradient(135deg, #2979ff 0%, #3b10e6 100%);
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 4px 15px rgba(41, 121, 255, 0.3);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(41, 121, 255, 0.4);

    .pulse-ring {
      animation-play-state: running;
    }

    .button-content {
      transform: scale(1.1);
    }
  }

  .button-content {
    position: relative;
    z-index: 2;
    transition: transform 0.3s ease;

    i {
      font-size: 16px;
      color: white;
      margin-bottom: 2px;
    }

    .ai-text {
      font-size: 16px;
      font-weight: bold;
      color: white;
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
    }
  }

  // 脉冲动画效果
  .pulse-ring {
    position: absolute;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background-color: rgba(41, 121, 255, 0.4);
    animation: pulse 2s infinite;
    animation-play-state: paused;
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 0.8;
  }
  70% {
    transform: scale(1.3);
    opacity: 0;
  }
  100% {
    transform: scale(1.3);
    opacity: 0;
  }
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 60vh;
  background: #f5f7fa;
  position: relative;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  padding-bottom: 180px;
}

.message {
  margin-bottom: 20px;
  display: flex;
  align-items: flex-start;

  &.user {
    flex-direction: row-reverse;

    .content {
      margin-right: 12px;
      background: #e8f5ff;
      border-radius: 20px 4px 20px 20px;
    }
  }

  &.assistant {
    .content {
      margin-left: 12px;
      background: white;
      border-radius: 4px 20px 20px 20px;
    }
  }

  .avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;

    &.ai-avatar {
      background: linear-gradient(135deg, #409eff, #2979ff);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-weight: bold;
    }
  }

  .content {
    max-width: 70%;
    padding: 12px 16px;
    font-size: 14px;
    line-height: 1.6;
    word-break: break-word;

    &.typing {
      .typing-indicator {
        margin-left: 8px;
        i {
          width: 4px;
          height: 4px;
          margin: 0 2px;
          background: #409eff;
          border-radius: 50%;
          display: inline-block;
          animation: blink 1.4s infinite;

          &:nth-child(2) {
            animation-delay: 0.2s;
          }
          &:nth-child(3) {
            animation-delay: 0.4s;
          }
        }
      }
    }
  }
}

.recommend-prompts {
  position: absolute;
  bottom: 90px;
  left: 0;
  right: 0;
  padding: 16px;
  background: white;
  border-top: 1px solid #ebeef5;
  z-index: 1;

  .recommend-title {
    font-size: 14px;
    color: #909399;
    margin-bottom: 12px;
  }

  .recommend-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
  }

  .recommend-item {
    padding: 8px 16px;
    background: #f5f7fa;
    border-radius: 20px;
    font-size: 14px;
    color: #606266;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background: #ecf5ff;
      color: #409eff;
    }
  }
}

.input-area {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background: white;
  border-top: 1px solid #ebeef5;
  z-index: 1;

  .input-wrapper {
    background: #f5f7fa;
    border-radius: 8px;
    padding: 12px;
  }
}

@keyframes blink {
  0%,
  100% {
    transform: scale(0.2);
    opacity: 0.2;
  }
  50% {
    transform: scale(1);
    opacity: 1;
  }
}
</style>
